package net;

import sun.plugin2.main.server.HeartbeatThread;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;



public class ThreadChatServer {
    // 定义服务端的ServerSocket属性
    private ServerSocket serverSocket;
    private List<PrintWriter> writerList = new ArrayList<>();

    public ThreadChatServer(){
        try {
            System.out.println("服务器启动");
            serverSocket = new ServerSocket(8080);
            System.out.println("服务器启动OK");

        }catch (IOException e){
            System.out.println("服务器启动失败");
            e.printStackTrace();
            System.exit(1);
        }

    }

    public class ClientHandle implements Runnable{
        private Socket socket;
        private String host;
        //    private int host;

        public ClientHandle(Socket socket){
            this.socket=socket;
            host=this.socket.getInetAddress().getHostAddress();
//        host=socket.getPort();
        }
        @Override
        public void run() {
            try {
                BufferedReader br = new BufferedReader(
                        new InputStreamReader(socket.getInputStream(), StandardCharsets.UTF_8));

                PrintWriter pw = new PrintWriter(
                        new BufferedWriter(
                                new OutputStreamWriter(socket.getOutputStream(),
                                        StandardCharsets.UTF_8)),true);

                writerList.add(pw);

                String data = null;
                while ((data=br.readLine())!=null){
                    System.out.println(host+"说:"+data);
                    for (PrintWriter out : writerList) {
                        out.println(host+"说:"+data);

                    }
                }

            }catch (IOException e){
                e.printStackTrace();
            }

        }
    }



    //启动服务读取数据
    public void start(){
        while (true) {
        try {

                Socket socket = serverSocket.accept();
                System.out.println("客户端连上了,Cline:" + socket);
               new Thread(new ClientHandle(socket)).start();
//                Thread thread2 = new Thread(new WriteHandle(socket));

//                thread2.start();
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
    public static void main(String[] args){
        new ThreadChatServer().start();

    }

}
